#  -*- coding:utf-8
'''

@File : sim_BI

@Author: 爸爸

@Date : 2020/02/28

@Desc :模拟BI设备端，client随机发数据
'''
import random
import socket
import struct
import threading
import time
import uuid

dev_status = [1, 2, 3, 4, 5, 6]


def ListenMsg(sc):
    count = 0
    while True:
        try:
            data = sc.recv(1024)
            data = [hex(i) for i in data]
            count += 1
            print(f"{sc.getsockname()} recv {count} :{data}")
        except Exception as e:
            print(count, e)
    pass


def CreateMsg(flag):
    res = [0x55, 0xff]
    v = []
    flag += 9
    if flag == 0x0a:
        s = uuid.uuid1().bytes
        v = [i for i in s]
    elif flag == 0x0d:
        v = [random.choice(dev_status)]
    elif flag == 0x0e:
        bag = random.randint(100, 500)
        v = list(struct.pack('i', bag))
    elif flag == 0x0f:
        s = "029030102-30402"
        v = [ord(i) for i in s]
    if len(v) == 0:
        res.extend([1, flag])
    else:
        res.append(len(v) + 2)
        res.append(flag)
        res.append(len(v))
        res.extend(v)
    return res
    pass


def SendMsg(sc):
    flags = [1, 2, 3, 4, 5, 6]
    count = 0
    while True:
        try:
            while True:
                index = random.randint(1, 6)
                msg = CreateMsg(index)
                if len(msg) > 0:
                    count += 1
                    sc.send(bytes(msg))
                time.sleep(1)
                print(f"{sc.getsockname()} send {count} :{[hex(i) for i in msg]}")
                time.sleep(30)
        except Exception as ex:
            print(ex)
    pass


ip = ('127.0.0.1', 10010)


def main():
    for i in range(1):
        sc = socket.socket()
        sc.connect(ip)
        threading.Thread(target=SendMsg, args=(sc,)).start()
        threading.Thread(target=ListenMsg, args=(sc,)).start()


if __name__ == '__main__':
    # msg = CreateMsg(4)
    # print(msg)
    # msg = CreateMsg(5)
    # print(msg)
    # msg = CreateMsg(1)
    # print(msg)
    main()

